package com.qf.base.service.impl;

import com.qf.base.domain.BaseCarrier;
import com.qf.base.domain.BaseDriver;
import com.qf.base.mapper.BaseCarrierMapper;
import com.qf.base.mapper.BaseDriverMapper;
import com.qf.base.service.IBaseDriverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BaseDriverServiceImpl implements IBaseDriverService {
    @Autowired
    private BaseDriverMapper baseDriverMapper;

    @Autowired
    private BaseCarrierMapper baseCarrierMapper;

    @Override
    public List<BaseDriver> selectDriverList(BaseDriver driver) {
        return baseDriverMapper.selectDriverList(driver);
    }

    // 新增 @Transactional 确保事务一致性，插入和同步要么都成功要么都失败
    @Transactional
    @Override
    public int insertDriver(BaseDriver baseDriver) {
        int result = baseDriverMapper.insertDriver(baseDriver);

        // 关键修复：只要插入成功（result > 0）且关联了承运商（carrierId != null），就执行同步
        if (result > 0 && baseDriver.getCarrierId() != null) {
            syncCarrierDriverCount(baseDriver.getCarrierId());
        }
        return result;
    }

    @Override
    public int updateDriver(BaseDriver driver) {
        return baseDriverMapper.updateDriver(driver);
    }

    @Override
    public BaseDriver selectDriverById(Long driverId) {
        return baseDriverMapper.selectDriverById(driverId);
    }

    @Transactional // 删除操作也需要事务保证
    @Override
    public int deleteDriverByIds(Long[] driverIds) {
        List<Long> carrierIds = baseDriverMapper.selectCarrierIdsByDriverIds(driverIds);
        int result = baseDriverMapper.deleteDriverByIds(driverIds);
        if (result > 0 && carrierIds != null && !carrierIds.isEmpty()) {
            carrierIds.forEach(this::syncCarrierDriverCount);
        }
        return result;
    }

    @Override
    public void syncCarrierDriverCount(Long carrierId) {
        // 增加承运商ID非空校验，避免空指针和无效SQL
        if (carrierId == null) {
            return;
        }
        int driverCount = baseDriverMapper.countByCarrierId(carrierId);
        BaseCarrier carrier = new BaseCarrier();
        carrier.setCarrierId(carrierId);
        carrier.setDriverCount((long) driverCount);
        baseCarrierMapper.updateDriverCount(carrier);
    }

    @Override
    public List<BaseDriver> getDriversByCarrierId(Long carrierId) {
        return baseDriverMapper.selectDriversByCarrierId(carrierId);
    }
}